package com.cykj.pos.controller.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.pos.domain.*;
import com.cykj.pos.mapper.FeiShunSettlementMapper;
import com.cykj.pos.service.*;
import com.cykj.pos.util.BigDecimalUtil;
import com.cykj.pos.util.DESHelperUtil;
import com.cykj.pos.util.FeiShunUtil;
import com.cykj.pos.websocket.server.WebSocketServer;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@Api(tags = "派达薪查询结算状态定时任务")
public class QuerySettlementStatusController {

    private final FeiShunSettlementMapper feiShunSettlementMapper;

    private final IBizCashoutRecordsService cashoutRecordsService;
    private final WebSocketServer webSocketServer;
    private final IBizMerchantService merchantService;
    private final IBizMerchBillService merchBillService;
    private final IBizWalletService walletService;
    private final IBizWithdrawalRecordsSpService iBizWithdrawalRecordsSpService;
    @Value("${cykj.path}")
    private String path;

//    @Scheduled(cron = "0 0/2 * * * ? ")
    public void querySettlementStatus() throws IOException {
        Properties properties = this.getMyProperty();
        if(!"2".equals(properties.getProperty("type"))){
//            System.out.println("**************查询结算状态定时任务不在此服务器执行*****************");
            return;
        }
        System.out.println("**************查询结算状态定时任务开始*****************");
        List<FeiShunSettlement> list= feiShunSettlementMapper.getlist();
        if(list.size()<=0){
            return;
        }
        Map map = new HashMap<>();
        map.put("username", FeiShunUtil.username);
        map.put("password", FeiShunUtil.password);
        map.put("remark","company");
        map.put("is",1);
        List listData=new ArrayList();
        for (FeiShunSettlement vo:list) {
            listData.add(vo.getTaskUserId());
        }
        try {
            //调用登录接口
            String data= FeiShunUtil.doPost(FeiShunUtil.logonUrl,null,JSONObject.toJSONString(map));
            JSONObject obj = JSONObject.parseObject(data);
            String accessToken = obj.getString("data");
            JSONObject accessTokenObj = JSONObject.parseObject(accessToken);
            String token=accessTokenObj.getString("access_token");

            //调用查询接口
            JSONObject resData= FeiShunUtil.send(FeiShunUtil.querySettUrl,token,JSONObject.toJSONString(listData));
            String code = resData.getString("code");
            String msg = resData.getString("msg");
            if("200".equals(code)){
                JSONArray arr=resData.getJSONArray("data");
                for (Object vo:arr) {
                    JSONObject jsonObject= (JSONObject) JSON.toJSON(vo);
                    String taskUserState=jsonObject.getString("taskUserState");
                    if("7".equals(taskUserState)||"8".equals(taskUserState)){//只有7结算成功和8结算失败进入
                        feishunWithdrawal(jsonObject,jsonObject.getString("errorMessage"));
                    }
                    String errorMessage=null;
                    if("8".equals(taskUserState)){
                        errorMessage=jsonObject.getString("errorMessage");
                    }else{
                        errorMessage=jsonObject.getString("taskUserStateStr");
                    }
                    String taskUserId=jsonObject.getString("taskUserId");
                    String url=jsonObject.getString("url");
                    String remark=jsonObject.getString("remark");
                    String fee=jsonObject.getString("fee");
                    feiShunSettlementMapper.updateTaskUser(taskUserState,errorMessage,url,taskUserId);
                }
            }else{
                System.out.println("**************查询结算状态定时任务执行失败原因："+msg+"*****************");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public String feishunWithdrawal(JSONObject jsonObject,String msg) {
        System.out.println("------------------------回调接收参数---------------------------");
        System.out.println(jsonObject);
        // 获得提现记录 通过orderNo
        FeiShunSettlement sett= feiShunSettlementMapper.getSett(jsonObject.getString("taskUserId"));
        BizCashoutRecords cashoutRecords = cashoutRecordsService.getCashoutRecordsByCustOrderNo(sett.getOrderNo());
        if(cashoutRecords==null){
            return "success";
        }
        Long userId = cashoutRecords.getCreateBy();
        // 处理自己的业务
        if (jsonObject.getString("taskUserState").equals("7")) {
            System.out.println("------------------------支付成功----------------------------");
            // 成功
            // 发消息
            String var3 = cashoutRecords.getVar3();
            String var4 = cashoutRecords.getVar4();
            BigDecimal serviceFee = new BigDecimal(var3);
            BigDecimal rateFee = new BigDecimal(var4);
            BigDecimal totalServiceFee = serviceFee.add(rateFee);
            BigDecimal orderAmt = cashoutRecords.getCashoutAmount().subtract(totalServiceFee);
            String walletAmount = cashoutRecords.getVar5();
            String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到" + cashoutRecords.getDealBank() +
                    ",提现订单号是：" + cashoutRecords.getVar2();
            System.out.println(paymentMess);
            BizMessageRecords paymentMessageRecords = new BizMessageRecords();
            paymentMessageRecords.setMsgContent(paymentMess);// 消息内容
            paymentMessageRecords.setMsgType(4); // 消息类型  4
            paymentMessageRecords.setReadStatus(0); // 消息未读
            paymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(userId, paymentMessageRecords);// 发送消息
            // 生账单
            BizMerchBill merchBill = new BizMerchBill();
            BizMerchant merchant = merchantService.getMerchantByUserId(userId); //商户信息
            merchBill.setMerchId(merchant.getMerchId());// 商户id
            merchBill.setMerchName(merchant.getMerchName());// 商户名称
            merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
            Date date = cashoutRecords.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
            merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
            merchBill.setAmount(cashoutRecords.getCashoutAmount().negate()); // 提现存的是负值
            merchBillService.save(merchBill); // 存账单数据
            // 提现记录  更新状态为 1
            cashoutRecords.setCashoutStatus("1");
            cashoutRecords.setVar1(jsonObject.getString("taskUserId"));//人员结算id
            cashoutRecords.setMsgId(paymentMessageRecords.getMsgId()); // 存储记录中对应的消息id
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            return "success";
        } else if(jsonObject.getString("taskUserState").equals("8")) {
            if (cashoutRecords.getIsRefund().equals("0")) {
                BizWallet wallet = walletService.getMyWalletByUserId(userId);
                String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
                String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
                String key = wallet.getSecretKey();// 获得key
                // 解密数据
                String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
                String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
                // 转换成BigDecimal类型
                BigDecimal profitAmount = new BigDecimal(profitAmountStr);
                BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
                // 预支付出去的金额为
                BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
                // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
                String cashoutType = cashoutRecords.getCashoutType();
                if ("1".equals(cashoutType)) {//1-结算账户
                    profitAmount = profitAmount.add(paymentMoney);
                } else if ("2".equals(cashoutType)) {//2-奖励账户
                    rewardAmount = rewardAmount.add(paymentMoney);
                }
                BigDecimal walletAmount = profitAmount.add(rewardAmount);
                // 加密
                String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
                String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
                String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
                wallet.setProfitAmount(profitAmountMoneyStr);
                wallet.setRewardAmount(rewardAmountMoneyStr);
                wallet.setWalletAmount(walletAmountMoneyStr);
                wallet.setSecretKey(key);
                // 保存钱包信息
                walletService.saveOrUpdate(wallet);
                // 发消息
                String paymentFailMess = "您的提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，提现订单号" +
                        cashoutRecords.getVar2() + "，失败原因：交易失败" + "---错误信息：" + msg;
                System.out.println(paymentFailMess);
                BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
                paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
                paymentFailMessageRecords.setMsgType(5); // 消息类型  5
                paymentFailMessageRecords.setReadStatus(0); // 消息未读
                paymentFailMessageRecords.setAdviceType(1); // 业务消息
                webSocketServer.sendInfo(userId, paymentFailMessageRecords);// 发送消息
                // 提现记录  更新状态为 0  失败
                cashoutRecords.setCashoutStatus("0");
                cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
                cashoutRecords.setErrorMsg("---错误信息：" + jsonObject.getString("msg"));// 存储失败原因
                cashoutRecords.setErrorMsg("1");
                cashoutRecordsService.saveOrUpdate(cashoutRecords);
            }
        }
        return "success";
    }
    /**
     * @author: haoran
     * @date: 2022/8/18
     * 方法名称： 读取配置文件，是否启动定时器内的方法
     */
    public Properties getMyProperty() throws IOException {
//        InputStream in = new BufferedInputStream(new FileInputStream("/var/cms.properties"));
        InputStream in = new BufferedInputStream(new FileInputStream(path+"/cms.properties"));
        Properties p = new Properties();
        p.load(in);
        return p;
    }

//    @Scheduled(fixedDelay = 10000)
    public void queryYlgWithdrawalStatus() throws IOException {
        Properties properties = this.getMyProperty();
        if(!"2".equals(properties.getProperty("type"))){
//            System.out.println("**************查询提现状态定时任务不在此服务器执行*****************");
            return;
        }
        System.out.println("**************查询提现状态定时任务开始*****************");
        List<BizYlgWithdrawalPoll> bizYlgWithdrawalPolls = walletService.getYlgWithdrawalList();
        for(BizYlgWithdrawalPoll bizYlgWith : bizYlgWithdrawalPolls){
            walletService.queryYlgWithdrawalStatus(bizYlgWith);
        }
    }


//    @Scheduled(cron = "30 0 0 * * ? ")// 每日凌晨0点0分30秒执行
    public void statisticsEveryDay() throws IOException {
        Properties properties = this.getMyProperty();
        if (!"2".equals(properties.getProperty("type"))) {
            System.out.println("**************日分润结算统计不在此服务器执行*****************");
            return;
        }
        System.out.println("**************日分润结算统计开始 "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"***服务器1*****************");
        iBizWithdrawalRecordsSpService.statisticsEveryDay();
        System.out.println("**************日分润结算统计完成 "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"***服务器1*****************");
    }
}
